{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d51a0fd3-2bd3-483c-a9e7-e7a99ce216a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.schema import (\n",
    "    AIMessage,\n",
    "    HumanMessage,\n",
    "    SystemMessage\n",
    ")\n",
    "\n",
    "# 国内代理方式\n",
    "llm = ChatOpenAI(\n",
    "    api_key = \"sk-y7DHfp9fzuCxOVm2158638099f9541D3833aB4F4Ed674aCf\",\n",
    "    base_url = \"https://vip.apiyi.com/v1\",    # 此处代理方式，如果是OpenAI官方接口需调整接口地址\n",
    "    model = \"gpt-4o-mini\",\n",
    "    max_tokens = 1000\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "607bd51d-aa66-4b3c-9011-c5c34d7729d6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "List five ice cream flavors.\n",
      "Your response should be a list of comma separated values, eg: `foo, bar, baz` or `foo,bar,baz`\n",
      "content='vanilla, chocolate, strawberry, mint, cookie dough' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 12, 'prompt_tokens': 41, 'total_tokens': 53, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_96c46af214', 'id': 'chatcmpl-BUuqgRFwKb7MIkbn69YDe8g9Ncbs6', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None} id='run--60aa43b6-6a89-4bd3-b35c-d0e6cc438def-0' usage_metadata={'input_tokens': 41, 'output_tokens': 12, 'total_tokens': 53, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "['vanilla', 'chocolate', 'strawberry', 'mint', 'cookie dough']"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.output_parsers import CommaSeparatedListOutputParser\n",
    "from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# 创建一个输出解析器，用于处理带逗号分割的列表输出\n",
    "output_parser = CommaSeparatedListOutputParser()\n",
    "\n",
    "# 获取格式化指令，该指令告诉LLM应该如何格式化输出\n",
    "format_instructions = output_parser.get_format_instructions()\n",
    "\n",
    "# 创建一个提示模板，它会基于给定的模板和变量来生成提示\n",
    "prompt_template = PromptTemplate(\n",
    "    template=\"List five {subject}.\\n{format_instructions}\",  # 模板内容\n",
    "    input_variables=[\"subject\"],  # 输入变量\n",
    "    partial_variables={\"format_instructions\": format_instructions}  # 预定义的变量，这里我们传入格式化指令\n",
    ")\n",
    "\n",
    "prompt = prompt_template.format(subject = \"ice cream flavors\")\n",
    "print(prompt)\n",
    "\n",
    "output = llm.invoke(prompt)\n",
    "print(output)\n",
    "\n",
    "output_parser.parse(output.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "271d4389-b0d5-48ae-9130-5ebfa9eccbb2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17141026-991a-49e3-89d9-4b2eaa982928",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "6005b740-a60b-4829-ad5a-0462e763980e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "List five ice cream flavors.\n",
      "Your response should be a list of comma separated values, eg: `foo, bar, baz` or `foo,bar,baz`\n",
      "2009-01-03 18:15:05\n"
     ]
    }
   ],
   "source": [
    "# 日期解析\n",
    "from langchain.output_parsers import DatetimeOutputParser\n",
    "from langchain.chains import LLMChain\n",
    "\n",
    "output_parser = DatetimeOutputParser()\n",
    "template = \"\"\"Answer the users question:\n",
    "\n",
    "{question}\n",
    "\n",
    "{format_instructions}\"\"\"\n",
    "\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    template,\n",
    "    partial_variables={\"format_instructions\": output_parser.get_format_instructions()},\n",
    ")\n",
    "print(prompt)\n",
    "# print(prompt.format(question=\"around when was bitcoin founded?\"))\n",
    "\n",
    "chain = prompt_template | llm\n",
    "output = chain.invoke(\"around when was bitcoin founded?\")\n",
    "print(output_parser.parse(output.content))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c60cb3ef-4d8f-4695-a42a-d142fcef7e93",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
